<!DOCTYPE html>
<html>

<head>
    <!-- <title>壁纸切换</title> -->
    <meta charset="utf-8" />
    <style>
        * {
            margin: 0;
            padding: 0;
            color: white;
        }
        
        p,
        input {
            border: none;
            background-color: darkslategray;
            line-height: 30px;
            border-radius: 5px;
        }
        
        input[type="button"] {
            width: 320px;
            margin: 10px;
            display: inline-block;
            text-align: center;
            background-color: brown
        }
        
        p,
        input[type="text"] {
            width: 320px;
            margin: 10px;
            height: 30px;
            padding-left: 4px;
        }
        
        html,
        body {
            height: 100%;
            width: 100%;
            min-width: 360px;
            /* padding: 5px; */
            background-color: rgba(39, 2, 39, 0.589)
        }
        
        body {
            text-align: center;
            box-sizing: border-box;
            padding: 5px;
        }
        
        .row {
            max-height: 150px;
            margin: 5px;
        }
        
        .col {
            height: 100%;
            display: inline-block;
            vertical-align: top;
        }
        
        .col li {
            list-style-type: none;
            margin: 20px 5px;
        }
        
        .img {
            width: 200px;
            height: 150px;
            overflow: hidden;
        }
    </style>
</head>

<body>


    <div class="row">
        <div class="col">
            <ul>
                <li>间隔时间(秒)</li>
                <li>
                    <input type="number" style="" value="15" name="time">
                </li>
                <li>
                    壁纸所在文件夹
                </li>
            </ul>
        </div>
        <div class="img col">
            <img src="../assets/img/default.jpg" alt="当前壁纸" title="当前壁纸">
        </div>
    </div>
    <div>
        <p onclick="choice(this)" style="display:inline-block;text-align:left">

        </p>
    </div>
    <div>
        <input type="button" value="开始" name="status" onclick="toogle(this)" />
    </div>
    <!-- <script src="change.js"></script> -->
    <script>
        const {
            dialog
        } = require('electron').remote
        const fs = require('fs');
        const path = require('path');
        const runtime = require('child_process');
        const configPath = path.join(__dirname, 'config.dat'); //配置文件位置



        function readConfig() {
            fs.closeSync(fs.openSync(configPath, 'a')); //创建文件，防止报错

            let data = fs.readFileSync(configPath, {
                encoding: 'utf-8'
            });
            if (data !== null) {
                //切分
                let datas = data.split('&');
                if (datas !== null && datas.length == 2) {
                    return {
                        time: parseInt(datas[0]),
                        dir: datas[1]
                    }
                    // this.time = parseInt(datas[0]);
                    // this.dir = datas[1];
                }
            }
            return null;

        }

        let index = -1;
        let imgs = [];
        //获取参数
        const data = readConfig();
        console.log(data);
        if (data != null) {
            document.getElementsByTagName('p')[0].innerHTML = data.dir;
            document.getElementsByName('time')[0].value = data.time;
            console.log('设置时间')
            console.log(document.getElementsByName('time')[0].value)
            readImg(data.dir);
        }

        function readImg(dir) {
            try {
                var stat = fs.statSync(dir);
                if (stat.isDirectory()) {
                    //读取图片
                    fs.readdir(dir, function (err, paths) {
                        if (err) return;
                        imgs = [];
                        for (var i = 0; i < paths.length; i++) { //提取图片文件
                            if (/\.(jpg|jpeg|png|bmp|gif)$/.test(paths[i])) {
                                imgs.push(paths[i]);
                            }
                        }
                        startExchange();
                    });
                } else {
                    document.getElementsByTagName('p')[0].innerHTML=('错误的路径')
                    // dialog.showMessageBox({
                    //     message: '错误的路径'
                    // });
                }
            } catch (e) {
                console.error(e);
                document.getElementsByTagName('p')[0].innerHTML=('错误的路径')
            }

        }

        function startExchange() {
            let dir = document.getElementsByTagName('p')[0].innerHTML
            let time = document.getElementsByName('time')[0].value

            if (imgs.length >= 2) {

                let dir = document.getElementsByTagName('p')[0].innerHTML
                let time = document.getElementsByName('time')[0].value
                fs.writeFileSync(configPath, time + "&" + dir);

                index = setInterval(function () {
                    let next = imgs[Math.floor(Math.random() * imgs.length)]
                    let real = (dir + path.sep + next);
                    //执行
                    runtime.exec('gsettings set com.deepin.wrap.gnome.desktop.background picture-uri \"' +
                        real + '\"');
                    exchangeListener(real);
                }, parseInt(time) * 1000);
                document.getElementsByTagName('input')[1].value = '暂停'
            }
        }

        function stopExchange() {
            document.getElementsByTagName('input')[1].value = '开始'
            clearInterval(index);
            index = -1;
        }

        function exchangeListener(path) {
            //获取图片地址
            var imgDom = document.getElementsByTagName('img')[0];

            var nImg = new Image();
            nImg.onload = function () {
                //获取图片真实宽高，进行计算，保证显示最多内容
                var realWidth = this.width;
                var realHeight = this.height;
                //获取父容器宽高
                var parentWidth = document.getElementsByClassName('img')[0].clientWidth;
                var parentHeight = document.getElementsByClassName('img')[0].clientHeight;

                //计算
                if ((realWidth / realHeight) > (parentWidth / parentHeight)) { //更宽，按照高度显示
                    imgDom.height = parentHeight;

                } else { //更高，按宽度显示
                    imgDom.width = parentWidth;
                }
                imgDom.src = 'file://' + path;
                imgDom.title = '当前图片：' + path.replace(document.getElementsByTagName('p')[0].innerHTML, '');
            }
            nImg.src = "file://" + path;
        }

        let chooseing = false;


        function choice(dom) {
            if (!chooseing && index === -1) { //停止状态方可选图片
                // 向主进程发送消息
                let _dom = dom;
                // ipcRenderer.send('open-directory-dialog');
                dialog.showOpenDialog({
                    properties: ["openDirectory"],
                    "defaultPath": "/media/inkbox/media/图片/壁纸"
                }, function (files) {
                    if (files) {
                        readImg(files[0]);
                        _dom.innerHTML = files[0];
                    }
                    chooseing = false;
                })
                chooseing = true;
            }
        }

        function toogle(dom) {
            if (index !== -1) {
                stopExchange();
            } else {

                startExchange();
            }
        }
    </script>
</body>

</html>